<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,body,#container{
            width:100%;
            height:100%;
        }
    </style>
</head>
<body>
    <div id="container">

    </div>
    <script>
        //发布订阅模式
        //也称作观察者模式，定义了对象间的一对多的依赖关系，
        //当一个对象的状态发 生改变时，所有依赖于它的对象都将得到通知
        //createStor dispatch subscribe
        class MyRedux{
            constructor(){
                this.container = []
            }
            getState(){
                return this.state
            }
            subscribe(fn){//订阅函数，订阅一些更新逻辑
                this.container.push(fn)
            }
            notify(value){//发布订阅
                this.container.forEach((fnItem)=>{
                    fnItem(value)
                })
            }
            dispatch(action){
                //调用reducer传入上次的state值,它的返回值覆盖上次的state
                this.state = this.reducer(this.state,action)
                //this.state如果发生了改变，那么就发布  immer
                this.notify(this.state)
            }
            //这里用户保存MyRedux实例,因为只有静态属性时共享的
            static instanceStor
            static createStor(reducer){
                if(MyRedux.instanceStor){
                    return MyRedux.instanceStor
                }else{
                    //实例化仓库
                    let store = new MyRedux()
                    //初次是state是undefined,reducer返回赋值给store,并挂载state
                    store.state = reducer(undefined,{})
                    //挂载reducer
                    store.reducer = reducer
                    //返回
                    return MyRedux.instanceStor = store
                }
            }
        }
        //声明初始值
        const defaultState = {
            username:'zhangsan'
        }
        //创建store仓库并传入reducer,store就是创建的仓库实例
        let stor = MyRedux.createStor((state=defaultState,action)=>{
            console.log(state,action);
            switch(action.type){
                case 'changename':
                    return {...state,username:action.value}
                default:
                    return {...state}
            }
        })
        //订阅仓库
        stor.subscribe((value)=>{
            console.log(value,'仓库值更新后同步刷新组件视图')
        })
        //
        console.log(stor.getState().username)
        //提交action
        stor.dispatch({
            type:'changename',
            value:'lisi'
        })
        console.log(stor.getState().username)
    </script>
</body>
</html>
